import axios from 'axios'
import { getErrorMessage } from '@/utils/error'

export enum ResultCode {
    Success = 200,
    Fail = 500
}

export interface GoodsArrivalInspectionDto {
    id: number
    inspectionSubject: string
    inspectionOrderNumber: string
    isSystemNumber: boolean
    inspectionDate: string
    inspectorId: number
    inspectorName?: string
    departmentId?: number
    departmentName?: string
    contactMethod?: string
    remarks?: string
    purchaseOrderNumber: string
    purchaseDate?: string
    supplierId: number
    supplierName?: string
    contactPerson?: string
    contactPhone?: string
    purchasingAgentId?: number
    purchasingAgentName?: string
    purchasingDepartmentId?: number
    purchasingDepartmentName?: string
    associatedProjectId?: number
    inspectionStatus?: string
    overallInspectionResult?: string
    createdBy: number
    createdAt: string
    lastModifiedBy?: number
    lastModifiedAt?: string
}

export interface GoodsArrivalInspectionDetailItemDto {
    id: number
    goodsArrivalInspectionId: number
    serialNumber: number
    itemNumber: string
    itemName: string
    specificationModel?: string
    unit?: string
    brand?: string
    purchaseQuantity: number
    inspectionType: string
    receivedQuantity: number
    inspectionQuantity: number
    qualifiedQuantity: number
    unqualifiedQuantity: number
    inspectionResult: string
    unqualifiedReason?: string
    inspectionRemarks?: string
}

export interface GoodsArrivalInspectionDetailDto extends GoodsArrivalInspectionDto {
    details: GoodsArrivalInspectionDetailItemDto[]
}

export interface APIPageing<T> {
    pageIndex: number
    pageSize: number
    totalCount: number
    totalPages: number
    pageData: T[]
}

export interface APIResult<T> {
    code: ResultCode
    message: string
    data: T
}

export interface GetGoodsArrivalInspectionListQuery {
    pageIndex: number
    pageSize: number
    inspectionSubject?: string
    inspectionOrderNumber?: string
    supplierId?: number
    inspectionStatus?: string
    inspectionDateStart?: string
    inspectionDateEnd?: string
    createdBy?: number
}

export interface CreateGoodsArrivalInspectionCommand {
    inspectionSubject: string
    isSystemNumber: boolean
    inspectionOrderNumber?: string
    inspectionDate: string
    inspectorId: number
    departmentId?: number
    contactMethod?: string
    remarks?: string
    purchaseOrderNumber: string
    purchaseDate?: string
    supplierId: number
    contactPerson?: string
    contactPhone?: string
    purchasingAgentId?: number
    purchasingDepartmentId?: number
    associatedProjectId?: number
    inspectionStatus?: string
    overallInspectionResult?: string
    createdBy: number
    details: Array<{
        serialNumber: number
        itemNumber: string
        itemName: string
        specificationModel?: string
        unit?: string
        brand?: string
        purchaseQuantity: number
        inspectionType: string
        receivedQuantity: number
        inspectionQuantity: number
        qualifiedQuantity: number
        unqualifiedQuantity: number
        inspectionResult: string
        unqualifiedReason?: string
        inspectionRemarks?: string
    }>
}

const apiClient = axios.create({
    baseURL: 'http://localhost:5000',
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' }
})

function normalize<T>(raw: any): APIResult<T> {
    const d = raw?.data || raw
    return { code: d?.code ?? d?.Code ?? ResultCode.Fail, message: d?.message ?? d?.Message ?? '', data: d?.data ?? d?.Data }
}

export const incomingInspectionApi = {
    async getList(params: GetGoodsArrivalInspectionListQuery): Promise<APIResult<APIPageing<GoodsArrivalInspectionDto>>> {
        try {
            const query = {
                PageIndex: params.pageIndex,
                PageSize: params.pageSize,
                InspectionSubject: params.inspectionSubject,
                InspectionOrderNumber: params.inspectionOrderNumber,
                SupplierId: params.supplierId,
                InspectionStatus: params.inspectionStatus,
                InspectionDateStart: params.inspectionDateStart,
                InspectionDateEnd: params.inspectionDateEnd,
                CreatedBy: params.createdBy
            }
            const raw = await apiClient.get('/api/GoodsArrivalInspection/list', { params: query })
            const n = normalize<APIPageing<GoodsArrivalInspectionDto>>(raw)
            const inner = n.data as any
            return {
                code: n.code, message: n.message, data: {
                    pageData: inner.pageData ?? inner.PageData ?? [],
                    totalCount: inner.totalCount ?? inner.TotalCount ?? 0,
                    pageIndex: inner.pageIndex ?? inner.PageIndex ?? query.PageIndex,
                    pageSize: inner.pageSize ?? inner.PageSize ?? query.PageSize,
                    totalPages: inner.totalPages ?? inner.TotalPages ?? 0
                }
            }
        } catch (e) {
            throw new Error(getErrorMessage(e))
        }
    },

    async getById(id: number): Promise<APIResult<GoodsArrivalInspectionDetailDto>> {
        const raw = await apiClient.get(`/api/GoodsArrivalInspection/${id}`)
        return normalize<GoodsArrivalInspectionDetailDto>(raw)
    },

    async create(command: CreateGoodsArrivalInspectionCommand): Promise<APIResult<number>> {
        try {
            const raw = await apiClient.post('/api/GoodsArrivalInspection', command)
            const n = normalize<number>(raw)
            return { code: n.code, message: n.message, data: n.data }
        } catch (e) {
            throw new Error(getErrorMessage(e))
        }
    }
} 